#coding=utf8
import urllib, re, urlparse
import cmrhelper
import decode

pre1 = re.compile('<script language="javascript" src=\'/js4/(.*?)\'></script>')
pre2 = re.compile('<script language="javascript" src=\'/js5/(.*?)\'></script>')
# pres = re.compile('<script language="javascript" src=\'/(\d*)/(.*?)\'></script>')
pres = re.compile('<script language="javascript" src=\'(/v/(.*?))\'></script>')


jsre = re.compile('src=\'(.*?)\'>')
cntre = re.compile('datas\[(\d*)\]')

def getpiclist(url,title='unamed',mylog=None):
    "parser html source and js codes to generate piclist"
    piclist = []
    content = ''
    try:
        content = urllib.urlopen(url).read()
        if content:
            if pres.findall(content) > 0:
                "fetch the js files which show the realpath of pictures"
                # jspaths = 'http://www.zxmh.net/%s/%s' % (pres.findall(content)[0][0],pres.findall(content)[0][1])
                jspaths = urlparse.urljoin('http://www.zxmh.net', pres.findall(content)[0][0])
                jssecondpath = cmrhelper.getcontent(jspaths,url)
                jssecondpath = jssecondpath.replace('\\','')
                jssecondlist = jsre.findall(jssecondpath)
                jscontent = ''
                for item in jssecondlist:
                    jspaths = urlparse.urljoin('http://www.zxmh.net', item)
                    jscontent += cmrhelper.getcontent(jspaths,url)
                # find chapter pages
                datas = [''] * (len(cntre.findall(jscontent)) + 1)
                # "exec the code from code"
                jscontent = jscontent.replace('var datas = new Array();\r\n','')
                jscontent = jscontent.replace(';','')
                jscontent = jscontent.replace('var ','')
                execlist = jscontent.split('\r\n')
                for item  in execlist:
                    exec(item)
                hostname = decode.decode64(pic_path)
                for i in range(1,len(datas)):
                    piclist.append([hostname + decode.decode64(datas[i]),url,title])
            elif pre1.findall(content) and pre2.findall(content):
                print '...'
            
        return piclist
    except  Exception, e:
        if mylog:
            mylog.writeLog(str(e)+'in getpiclist','error')
        return None
